/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.wx.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.common.BusinessUtils;
import com.jeesite.modules.common.QiniuUtils;
import com.jeesite.modules.common.refun.CollectionUtil;
import com.jeesite.modules.common.refun.StringUtil;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.test.entity.TestTree;
import com.jeesite.modules.wx.entity.*;
import com.jeesite.modules.wx.service.*;
import com.qiniu.common.QiniuException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import org.springframework.web.util.HtmlUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * wx_activityController
 * @author wangjianxin
 * @version 2018-09-28
 */
@Controller
@RequestMapping(value = "${adminPath}/wx/wxActivity")
@Slf4j
public class WxActivityController extends BaseController {

	@Autowired
	private WxActivityService wxActivityService;
	@Autowired
	private WxBusinessService wxBusinessService;
	@Autowired
	private WxUserDisValueRecordService wxUserDisValueRecordService;
	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private WxActivityDisUserService wxActivityDisUserService;
	@Autowired
	private WxBusinessGroupOrgConfigService wxBusinessGroupOrgConfigService;

	@Value("${api.img.path}")
	private String imgPath;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public WxActivity get(String id, boolean isNewRecord) {
		WxActivity wxActivity = wxActivityService.get(id, isNewRecord);
		//添加分组
		WxBusinessGroupOrgConfig wxBusinessGroupOrgConfig = new WxBusinessGroupOrgConfig();
		Employee employee = (Employee) UserUtils.getUser().getRefObj();
		wxBusinessGroupOrgConfig.setOfficeCode(employee.getOffice().getOfficeCode());
		List<WxBusinessGroupOrgConfig> list = wxBusinessGroupOrgConfigService.findList(wxBusinessGroupOrgConfig);
		wxActivity.setWxBusinessGroupOrgConfigList(list);
		return wxActivity;
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("wx:wxActivity:view")
	@RequestMapping(value = {"list", ""})
	public String list(WxActivity wxActivity, Model model) {
		model.addAttribute("wxActivity", wxActivity);
		return "modules/wx/wxActivityList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("wx:wxActivity:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<WxActivity> listData(WxActivity wxActivity, HttpServletRequest request, HttpServletResponse response) {
		Page<WxActivity> page = wxActivityService.findPage(new Page<WxActivity>(request, response), wxActivity);


		//查询活动的支出和收入
		List<WxActivity> wxActivityList = page.getList();
		for(WxActivity temp : wxActivityList){

			String activityId = temp.getId();

			//查询该活动的支出
			WxActivityDisUser wxActivityDisUser = new WxActivityDisUser();
			wxActivityDisUser.setActivityId(activityId);
			List<WxActivityDisUser> wxActivityDisUserList = wxActivityDisUserService.findList(wxActivityDisUser);
			Map map = new HashMap<>();
			if(CollectionUtil.isNotEmpty(wxActivityDisUserList)){
				for(WxActivityDisUser t : wxActivityDisUserList){
					map.put(t.getUserId(),t.getUserOpenId());
				}
			}


			//查询收入
			WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
			//活动id
			wxUserDisValueRecord.setBuyActivityId(Long.valueOf(activityId));
			wxUserDisValueRecord.setBuyFlag(1);
			List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);
			//总收入
			BigDecimal amountIn = BigDecimal.ZERO;
			//总支出
			BigDecimal amountOut = BigDecimal.ZERO;
			for(WxUserDisValueRecord t : wxUserDisValueRecordList){

				amountIn = amountIn.add(t.getBuyPrice());
				//支出，返佣的
				if(StringUtil.isNotEmpty(t.getUserOpenId()) && map.containsKey(t.getUserId())){
					if(null != t.getDisMoneyValue()){
						amountOut = amountOut.add(t.getDisMoneyValue());
					}
				}
			}

			temp.setAmountOut(amountOut);
			temp.setAmountIn(amountIn);
		}

		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("wx:wxActivity:view")
	@RequestMapping(value = "form")
	public String form(WxActivity wxActivity, Model model) {

		//查询已经入住的商家
		List<WxBusiness> wxBusinessList = wxBusinessService.findList(new WxBusiness());
//		List<WxBusiness> list = new LinkedList<>();
//		WxBusiness wxBusiness1 = new WxBusiness();
//		WxBusiness wxBusiness2 = new WxBusiness();
//		WxBusiness wxBusiness3 = new WxBusiness();
//		wxBusiness1.setName("丽雅");
//		list.add(wxBusiness1);
//
//		wxBusiness2.setName("唯颜");
//		list.add(wxBusiness2);
//
//		wxBusiness3.setName("焕玉");
//		list.add(wxBusiness3);

		model.addAttribute("wxBusinessList", wxBusinessList);

		//返回加上H5地址
		if(null != wxActivity && StringUtils.isNotEmpty(wxActivity.getId())){
			wxActivity.setActivityH5Url(BusinessUtils.getInitFrontServer()+wxActivity.getId()+"/99");
			model.addAttribute("activityH5Url", wxActivity.getActivityH5Url());

		}

		model.addAttribute("wxActivity", wxActivity);
		return "modules/wx/wxActivityForm";
	}

	/**
	 * 保存wx_activity
	 */
	@RequiresPermissions("wx:wxActivity:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated WxActivity wxActivity) {



		//入群二维码
		String groupPic = wxActivity.getGroupPic();
		//海报
		String bannerPic = wxActivity.getBannerPic();
		//分享二维码
		String sharePic = wxActivity.getSharePic();
		//bgm
		String bgm = wxActivity.getBgm();
		//分享banner
		String inviteBannerPic = wxActivity.getInviteBannerPic();

//		//坐标位置错误保存失败
//		String qrIndex = wxActivity.getQrIndex();
//		String headImgINdex = wxActivity.getHeadImgIndex();
//		String userNameIndex = wxActivity.getUserNameIndex();
//		if(!qrIndex.contains(",") || !headImgINdex.contains(",") || !userNameIndex.contains(",")){
//			//失败
//			return renderResult(Global.FALSE, text("保存活动失败，坐标格式填写错误，请按照 80,200 的格式填写！"));
//		}

		//二维码坐标
		wxActivity.setQrIndex("2,648");
		//头像坐标
		wxActivity.setHeadImgIndex("135,660");
		//用户名坐标
		wxActivity.setUserNameIndex("208,680");

		/**
		 * 坐标写死
		 */
		//上传图片到七牛云
		if(StringUtils.isNotEmpty(groupPic)){
			File file = new File(imgPath+groupPic);
			String groupPicName = file.getName();
			logger.info("upload groupPic file name:"+groupPicName);
			try {
				String picUrl = QiniuUtils.upload(file, groupPicName);
				logger.info(picUrl);
				wxActivity.setGroupPic(picUrl);
			} catch (QiniuException e) {
				logger.error("上传活动入群二维码到七牛云失败={}",e.getMessage());
				e.printStackTrace();
			}

		}

		if(StringUtils.isNotEmpty(bannerPic)){

			File file = new File(imgPath+bannerPic);
			String bannerPicName = file.getName();
			logger.info("upload bannerPic file name:"+bannerPicName);
			try {
				String picUrl = QiniuUtils.upload(file, bannerPicName);
				logger.info(picUrl);
				wxActivity.setBannerPic(picUrl);
			} catch (QiniuException e) {
				logger.error("上传活动海报到七牛云失败={}",e.getMessage());
				e.printStackTrace();
			}

		}

		if(StringUtils.isNotEmpty(sharePic)){

			File file = new File(imgPath+sharePic);
			String sharePicName = file.getName();
			logger.info("upload sharePic file name:"+sharePicName);
			try {
				String picUrl = QiniuUtils.upload(file, sharePicName);
				logger.info(picUrl);
				wxActivity.setSharePic(picUrl);
			} catch (QiniuException e) {
				logger.error("上传活动分享图片到七牛云失败={}",e.getMessage());
				e.printStackTrace();
			}
		}

		if(StringUtil.isNotEmpty(bgm)){
			File file = new File(imgPath+bgm);
			String bgmResource = file.getName();
			logger.info("upload bgm file name:"+bgmResource);
			try {
				String picUrl = QiniuUtils.upload(file, bgmResource);
				logger.info(picUrl);
				wxActivity.setBgm(picUrl);
			} catch (QiniuException e) {
				logger.error("上传活动bgm图片到七牛云失败={}",e.getMessage());
				e.printStackTrace();
			}
		}
		if(StringUtil.isNotEmpty(inviteBannerPic)){
			File file = new File(imgPath+inviteBannerPic);
			String bgmResource = file.getName();
			logger.info("upload inviteBannerPic file name:"+bgmResource);
			try {
				String picUrl = QiniuUtils.upload(file, bgmResource);
				logger.info(picUrl);
				wxActivity.setInviteBannerPic(picUrl);
			} catch (QiniuException e) {
				logger.error("上传活动inviteBannerPic图片到七牛云失败={}",e.getMessage());
				e.printStackTrace();
			}
		}

		//页面转译
		wxActivity.setRule(HtmlUtils.htmlUnescape(wxActivity.getRule()));
		wxActivityService.save(wxActivity);

		return renderResult(Global.TRUE, text("保存活动成功！"));
	}
	
	/**
	 * 删除wx_activity
	 */
	@RequiresPermissions("wx:wxActivity:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(WxActivity wxActivity) {
		wxActivityService.delete(wxActivity);
		return renderResult(Global.TRUE, text("删除活动成功！"));
	}


	/**  购买活动 **/

	/**
	 * 查询列表
	 */
	@RequiresPermissions("wx:wxActivity:view")
	@RequestMapping(value = "pay")
	public String byActivity(WxActivity wxActivity, Model model) {
		model.addAttribute("wxActivity", wxActivity);
		return "modules/wx/wxPayActivityList";
	}

	/**
	 * 查看购买的人数
	 * @param wxActivity
	 * @param model
	 * @return
	 */
	@RequiresPermissions("wx:wxActivity:view")
	@RequestMapping(value = "user")
	public String user(WxActivity wxActivity, Model model) {
		model.addAttribute("wxActivity", wxActivity);

		return "modules/wx/wxUserActivityList";
	}

	/**
	 * 查询列表数据
	 * 查询购买该活动的用户list
	 */
	@RequiresPermissions("wx:wxActivity:view")
	@RequestMapping(value = "listPayUserData")
	@ResponseBody
	public Page<WxUserDisValueRecord> listPayUserData(WxActivity wxActivity, HttpServletRequest request, HttpServletResponse response) {
		log.info("获得活动id={}",wxActivity.getId());

		WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
		wxUserDisValueRecord.setBuyActivityId(Long.valueOf(wxActivity.getId()));

//		List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);

		Page<WxUserDisValueRecord> page = wxUserDisValueRecordService.findPage(new Page<WxUserDisValueRecord>(request, response), wxUserDisValueRecord);
		List<WxUserDisValueRecord> wxUserDisValueRecordList = page.getList();

		if(CollectionUtils.isNotEmpty(wxUserDisValueRecordList)){

			for(WxUserDisValueRecord temp : wxUserDisValueRecordList){

				//查询该活动下购买的用户详细信息
				String userId = temp.getBuyUserId().toString();
				WxUser wxUser = wxUserService.get(userId);
				temp.setWxUser(wxUser);

				//查询活动详情信息
				String activityId = temp.getBuyActivityId().toString();
				WxActivity findIdByActivity = wxActivityService.get(activityId);
				temp.setWxActivity(findIdByActivity);
			}

		}


		return page;
	}

	/**
	 * 查询机构下的所有活动
	 * @return
	 */
	@RequestMapping("/getActivityListByOrg")
	@ResponseBody
	public List<WxActivity> getActivityListByOrg(){
		Employee employee = (Employee) UserUtils.getUser().getRefObj();
		WxActivity wxActivity = new WxActivity();
		wxActivity.setOfficeCode(employee.getOffice().getOfficeCode());
		List<WxActivity> list = wxActivityService.findList(wxActivity);
		return list;
	}

	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		Employee employee = (Employee) UserUtils.getUser().getRefObj();
		WxActivity wxActivity = new WxActivity();
		wxActivity.setOfficeCode(employee.getOffice().getOfficeCode());
		List<WxActivity> list = wxActivityService.findList(wxActivity);
		for (int i=0; i<list.size(); i++){
			WxActivity e = list.get(i);
			// 过滤非正常的数据
			if (!TestTree.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("name", e.getTitle());
			mapList.add(map);
		}
		return mapList;
	}

	
}